package com.o2o.app.userCenter;

/**
 * 注册- 基本信息
 */
import java.io.ByteArrayOutputStream;
import java.io.File;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.o2o.app.R;
import com.o2o.app.utils.DataUtil;
import com.o2o.app.utils.FileUtil;
import com.o2o.app.utils.PhoneUtil;
import com.o2o.app.utils.SendCacheManager;

public class UserInfoActivity extends Activity {
	// 跳转姓名
	private static int FORUSERITEMNAME = 5555;
	// 跳转昵称
	private static int FORUSERITEMNICK = 5556;
	// 个性签名
	private static int FORUSERITEMDIY = 5557;
	// 性别
	private static int FORUSERITEMSEX = 5558;

	public static final int GALLERY_ACTIVITY = 1002;
	public static final int CAMERA_ACTIVITY = 1001;
	/**
	 * 返回按钮
	 */
	private Button btn_back;

	/**
	 * 真实姓名布局
	 */
	private RelativeLayout rlt_realname;

	/**
	 * 真实名字
	 */
	private TextView tv_realname;

	/**
	 * 昵称布局
	 */
	private RelativeLayout rlt_nickname;

	/**
	 * 昵称名字
	 */
	private TextView tv_nickname;

	/**
	 * 个性签名布局
	 */
	private RelativeLayout rlt_diyinfo;

	/**
	 * 个性签名
	 */
	private TextView tv_diyinfo;

	/**
	 * 性别布局
	 */
	private RelativeLayout rlt_sex;

	/**
	 * 性别
	 */
	private TextView tv_sex;

	/**
	 * 生日布局
	 */
	private RelativeLayout rlt_birthday;

	/**
	 * 生日控件
	 */
	private RelativeLayout rlt_date;

	/**
	 * 生日取消按钮
	 */
	private LinearLayout llt_cancel;

	/**
	 * 生日保存按钮
	 */
	private LinearLayout llt_save;

	/**
	 * 时间控件
	 */
	private DatePicker datepicker;

	/**
	 * 生日字符串
	 */
	private String date;

	/**
	 * 生日显示
	 */
	private TextView tv_birthday;

	/**
	 * 头像布局
	 */
	private RelativeLayout rlt_pic;

	/**
	 * 拍照布局
	 */
	private LinearLayout llt_01;

	/**
	 * 取消按钮
	 */
	private LinearLayout lly_cancel;

	/**
	 * 拍照那妞
	 */
	private LinearLayout lly_pic;

	/**
	 * 从手机相册选择
	 */
	private LinearLayout lly_img;

	/**
	 * 头像
	 */
	private ImageView iv_user_pic;

	/**
	 * Bitmap工厂中的Options对象，用于重绘Bitmap对象
	 */
	private BitmapFactory.Options opts = new BitmapFactory.Options();
	// bitmap资源
	private Bitmap bitmap = null;

	// 图片的二进制资源
	private byte[] picRes = null;

	// 文件大小
	private int picSize = 0;

	// 图片文件
	private String picPath = null;

	private Bitmap newbitmap = null;

	/**
	 * 下一步按钮
	 */
	private Button btn_fpass;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_info);

		initViews();
	}

	private void initViews() {
		// 下一步
		btn_fpass = (Button) findViewById(R.id.btn_fpass);
		btn_fpass.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UserInfoActivity.this,
						MineUserCenterActivity.class);
				startActivity(intent);
				finish();
			}
		});

		// 返回按钮
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		// 真实名字布局
		rlt_realname = (RelativeLayout) findViewById(R.id.rlt_realname);
		rlt_realname.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UserInfoActivity.this,
						UserInfoItemActivity.class);
				intent.putExtra("title", "名字");
				startActivityForResult(intent, FORUSERITEMNAME);
			}
		});

		// 真实名字
		tv_realname = (TextView) findViewById(R.id.tv_realname);

		// 昵称布局
		rlt_nickname = (RelativeLayout) findViewById(R.id.rlt_nickname);
		rlt_nickname.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UserInfoActivity.this,
						UserInfoItemActivity.class);
				intent.putExtra("title", "昵称");
				startActivityForResult(intent, FORUSERITEMNICK);
			}
		});

		// 昵称
		tv_nickname = (TextView) findViewById(R.id.tv_nickname);

		// 个性签名布局
		rlt_diyinfo = (RelativeLayout) findViewById(R.id.rlt_diyinfo);
		rlt_diyinfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UserInfoActivity.this,
						UserInfoItemActivity.class);
				intent.putExtra("title", "个性签名");
				startActivityForResult(intent, FORUSERITEMDIY);
			}
		});

		// 个性签名
		tv_diyinfo = (TextView) findViewById(R.id.tv_diyinfo);

		// 性别布局
		rlt_sex = (RelativeLayout) findViewById(R.id.rlt_sex);
		rlt_sex.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UserInfoActivity.this,
						UserInfoSexActivity.class);
				intent.putExtra("title", "性别");
				startActivityForResult(intent, FORUSERITEMSEX);
			}
		});

		// 性别
		tv_sex = (TextView) findViewById(R.id.tv_sex);

		// 生日按钮
		rlt_birthday = (RelativeLayout) findViewById(R.id.rlt_birthday);
		rlt_birthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				rlt_date.setVisibility(View.VISIBLE);
			}
		});

		// 生日控件
		rlt_date = (RelativeLayout) findViewById(R.id.rlt_date);

		// 生日取消按钮
		llt_cancel = (LinearLayout) findViewById(R.id.llt_cancel);
		llt_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				rlt_date.setVisibility(View.GONE);
			}
		});

		// 生日保存按钮
		llt_save = (LinearLayout) findViewById(R.id.llt_save);
		llt_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				rlt_date.setVisibility(View.GONE);
				date = datepicker.getYear() + "-" + (datepicker.getMonth() + 1) + "-"
						+ datepicker.getDayOfMonth();
				tv_birthday.setText(date);
			}
		});

		datepicker = (DatePicker) findViewById(R.id.datepicker);

		tv_birthday = (TextView) findViewById(R.id.tv_birthday);

		// 头像布局
		rlt_pic = (RelativeLayout) findViewById(R.id.rlt_pic);
		rlt_pic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				llt_01.setVisibility(View.VISIBLE);
			}
		});

		llt_01 = (LinearLayout) findViewById(R.id.llt_01);

		// 取消按钮
		lly_cancel = (LinearLayout) findViewById(R.id.lly_cancel);
		lly_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				llt_01.setVisibility(View.GONE);
			}
		});

		// 拍照
		lly_pic = (LinearLayout) findViewById(R.id.lly_pic);
		lly_pic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				tockenPicFromCamera();
			}
		});

		lly_img = (LinearLayout) findViewById(R.id.lly_img);
		lly_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				getPicFromLocal();
			}
		});

		// 头像
		iv_user_pic = (ImageView) findViewById(R.id.iv_user_pic);
	}

	/**
	 * 拍照选择图片
	 */
	private void tockenPicFromCamera() {
		try {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
					.fromFile(new File(Environment
							.getExternalStorageDirectory(), "/temp.jpg")));
			startActivityForResult(cameraIntent, CAMERA_ACTIVITY);
		} catch (ActivityNotFoundException e) {
			Log.i("[SendMBlogActivity------>tockenPicFromCamera()]:",
					"Activity Not Found Exception", e);
		}
	}

	/**
	 * 从本地获取图片
	 * 
	 * @return
	 */
	private void getPicFromLocal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.addCategory(Intent.CATEGORY_OPENABLE);
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(localIntent2, GALLERY_ACTIVITY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == FORUSERITEMNAME && data != null) {

			tv_realname.setText(data.getStringExtra("realname"));
		} else if (requestCode == FORUSERITEMNICK && data != null) {

			tv_nickname.setText(data.getStringExtra("nickname"));
		} else if (requestCode == FORUSERITEMDIY && data != null) {

			tv_diyinfo.setText(data.getStringExtra("diyinfo"));
		} else if (requestCode == FORUSERITEMSEX && data != null) {

			if ("0".equals(data.getStringExtra("sex"))) {
				tv_sex.setText("男");
			} else {
				tv_sex.setText("女");
			}

		} else if (RESULT_OK != resultCode) {
			return;
		} else {
			DataUtil.setFriendsName("");
			switch (requestCode) {
			case CAMERA_ACTIVITY: {
				opts.inSampleSize = 3;
				if (bitmap != null) {
					bitmap.recycle();
				}
				bitmap = BitmapFactory
						.decodeFile(Environment.getExternalStorageDirectory()
								+ "/temp.jpg", opts);

				SendCacheManager.setBitmapCache(bitmap);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, 80, stream);
				picRes = stream.toByteArray();
				picSize = stream.size();

				DataUtil.setPicRes(picRes);
				DataUtil.setPicSize(picSize);
				DataUtil.setPicPath(Environment.getExternalStorageDirectory()
						+ "/temp.jpg");

				// 自动旋转
				int degree = PhoneUtil.readPictureDegree(DataUtil.getPicPath());
				newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);

				Drawable drawable = new BitmapDrawable(newbitmap);

				iv_user_pic.setBackgroundDrawable(drawable);

			}
				break;
			case GALLERY_ACTIVITY: {
				// 清理图片资源
				clearImage();

				Uri selectedImageUri = null;
				try {
					selectedImageUri = data.getData();

					// 获取图库图片
					getPicFromUri(selectedImageUri);

					if (selectedImageUri != null) {
						try {
							opts.inSampleSize = 3;
							if (bitmap != null) {
								bitmap.recycle();
							}
							bitmap = BitmapFactory.decodeStream(
									getContentResolver().openInputStream(
											selectedImageUri), null, opts);

						} catch (Exception e) {

						}
					}

					SendCacheManager.setBitmapCache(bitmap);
					int degree = PhoneUtil.readPictureDegree(DataUtil
							.getPicPath());
					newbitmap = PhoneUtil.rotaingImageView(degree, bitmap);
					// iv_pic.setImageBitmap(bitmap);
					Drawable drawable = new BitmapDrawable(newbitmap);

					iv_user_pic.setBackgroundDrawable(drawable);
				} catch (Exception e) {
				}
			}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 获取图片名
	 * 
	 * @param uri
	 *            图片的URI
	 */
	private void getPicFromUri(Uri uri) {
		try {
			String[] data = { MediaStore.Images.Media.DATA };
			@SuppressWarnings("deprecation")
			Cursor cursor = managedQuery(uri, data, null, null, null);
			if (cursor != null) {
				int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				picPath = cursor.getString(index);
			} else {
				picPath = Uri.decode(uri.toString());
				picPath = picPath.replace("file://", "");
			}
			File file = new File(picPath);
			picSize = (int) file.length();
			picRes = FileUtil.getFileBytes(picPath);

			DataUtil.setPicPath(picPath);
			DataUtil.setPicRes(picRes);
			DataUtil.setPicSize(picSize);
		} catch (Exception e) {
		}

	}

	/**
	 * 清理图片资源
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void clearImage() {
		DataUtil.setPicRes(null);
		DataUtil.setPicSize(0);
		DataUtil.setPicPath("");
	}

}
